from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from datetime import date

try:
    from pyaws import ecs
    CAN_PERFORM_AMAZON_LOOKUP = getattr(settings, 'AMAZON_AWS_KEY', False)
except ImportError:
    CAN_PERFORM_AMAZON_LOOKUP = False

if CAN_PERFORM_AMAZON_LOOKUP:
    ecs.setLicenseKey(CAN_PERFORM_AMAZON_LOOKUP)

PROGRESS_CHOICES = (
    ('p', 'Page'),
    ('c', 'Chapter'),
)

class Author(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    slug = models.SlugField()
    website = models.URLField(blank=True)

    def __unicode__(self):
        return u'%s, %s' % (self.last_name, self.first_name)

    def get_absolute_url(self):
        return reverse('bibliophile-author', args=[self.slug])

    def url_name(self):
        return mark_safe(u'<a href="%s">%s %s</a>' % (self.get_absolute_url(),
                                                      self.first_name,
                                                      self.last_name))

    def _books_on_file(self):
        return self.book_set.count()
    books_on_file = property(_books_on_file)

    class Meta:
        ordering = ('last_name', 'first_name')

class Book(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)
    author = models.ManyToManyField(Author, blank=True)
    description = models.TextField(blank=True)
    isbn_10 = models.CharField('ISBN-10', max_length=10, blank=True)
    amazon_lookup = models.BooleanField('Look this book up on Amazon?', default=False, blank=True, editable=CAN_PERFORM_AMAZON_LOOKUP)
    show_progress = models.BooleanField(default=True, blank=True)
    progress_mode = models.CharField(max_length=1, choices=PROGRESS_CHOICES, default='p')
    maximum_progress = models.PositiveIntegerField(help_text="The number of pages or chapters in the book, depending on your chosen progress mode.", default=0)
    date_added = models.DateField(auto_now_add=True)
    date_updated = models.DateField(auto_now=True)

    def __unicode__(self):
        return self.title #u'%s by %s' % (self.title, self.author_string)

    def _progress(self):
        try:
            value = self.progress_set.order_by('-milestone')[0].milestone
        except IndexError:
            value = 0

        return (float(value) / self.maximum_progress) * 100
    progress = property(_progress)

    def date_finished(self):
        if self.progress >= 100:
            return self.progress_set.order_by('-milestone')[0].date_achieved
        return None

    def _clean_author_string(self):
        return u', '.join([unicode(a) for a in self.author.all()])
    authors = property(_clean_author_string)

    def _author_string(self):
        return mark_safe(u', '.join([a.url_name() for a in self.author.all()]))
    author_string = property(_author_string)

    def get_amazon_data(self):
        if not hasattr(self, 'amazon_data'):
            self.amazon_data = ecs.ItemLookup(self.isbn_10)[0]

    def amazon_url(self):
        self.get_amazon_data()
        return self.amazon_data.DetailPageURL

    def price(self):
        self.get_amazon_data()
        cart = ecs.CartCreate([self.amazon_data], (1,))
        return cart.CartItems[0].Price.FormattedPrice

    class Meta:
        ordering = ['-date_added', 'title']

class Progress(models.Model):
    book = models.ForeignKey(Book)
    milestone = models.PositiveIntegerField()
    date_achieved = models.DateField(default=date.today)

    def __unicode__(self):
        return 'Progressed to %s %i of %i in %s' % (
                    self.book.get_progress_mode_display().lower(),
                    self.milestone,
                    self.book.maximum_progress,
                    self.book.title
                )

    class Meta:
        ordering = ['-date_achieved', 'book', '-milestone']
        verbose_name_plural = 'progress'
